<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish">
    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name"/>
    </a-form-item>
    <a-form-item label="合金代码" name="alloy_code">
      <a-select
          v-model:value="ruleForm.alloy_code"
          style="width: 120px"
          ref="select"
      >
        <a-select-option
            v-for="item in alloyCodeSelectionOptions"
            :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="数据来源" name="data_source">
      <a-input v-model:value="ruleForm.data_source"/>
    </a-form-item>
    <a-form-item label="样品状态" name="sample_status">
      <a-input v-model:value="ruleForm.sample_status"/>
    </a-form-item>
    <a-form-item label="设备名称" name="equipment_name">
      <a-input v-model:value="ruleForm.equipment_name"/>
    </a-form-item>
    <a-form-item label="设备厂家" name="equipment_manufacturer">
      <a-input v-model:value="ruleForm.equipment_manufacturer"/>
    </a-form-item>
    <a-form-item label="设备型号" name="device_model">
      <a-input v-model:value="ruleForm.device_model"/>
    </a-form-item>
    <a-form-item label="温度" name="temperature">
      <a-input v-model:value="ruleForm.temperature"/>
    </a-form-item>
    <a-form-item label="标距" name="sample_range">
      <a-input v-model:value="ruleForm.sample_range"/>
    </a-form-item>
    <a-form-item label="宽度" name="sample_width">
      <a-input v-model:value="ruleForm.sample_width"/>
    </a-form-item>
    <a-form-item label="厚度" name="sample_thickness">
      <a-input v-model:value="ruleForm.sample_thickness"/>
    </a-form-item>
    <a-form-item label="开口深度" name="open_depth">
      <a-input v-model:value="ruleForm.open_depth"/>
    </a-form-item>
    <a-form-item label="开口形状" name="open_shape">
      <a-input v-model:value="ruleForm.open_shape"/>
    </a-form-item>
    <a-form-item label="断裂韧性" name="fracture_toughness">
      <a-input v-model:value="ruleForm.fracture_toughness"/>
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import {message} from 'ant-design-vue'

export default {
  name: 'AddOrEditFractureProperty',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  data() {
    // validStr 不包含空格
    let validateAlloyName = async (rule, value) => {
      if (value === ''){
        return Promise.reject('请选择合金代码')
      }
    }
    return {
      ruleForm: {
        sample_name: '',
        alloy_code: '',
        data_source: '',
        sample_status: '',
        equipment_name: '',
        equipment_manufacturer: '',
        device_model: '',
        temperature: '',
        sample_range: '',
        sample_width: '',
        sample_thickness: '',
        open_depth: '',
        open_shape: '',
        fracture_toughness: '',
      },
      rules: {
        alloy_code: [
          {
            validator: validateAlloyName,
            trigger: 'change',
            required: true,
            whiteSpace: true,
          }
        ],
      },
      layout: {
        labelCol: {span: 4},
        wrapperCol: {span: 14},
      },
      submitting: false,
      alloyCodeSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.alloyCodeSelectionOptions = []
      this.axios
          .get('/attachment_management/alloy_phase_diagram/')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              this.alloyCodeSelectionOptions.push({
                url: data[i].url,
                label: data[i].alloy_code,
              })
            }
            this.ruleForm.alloy_code = data.length === 0 ? '' : data[0].url
            if (this.url !== '') {
              this.axios
                  .get(this.url)
                  .then((res) => {
                    const data = res.data
                    this.ruleForm.sample_name = data.sample_name
                    this.ruleForm.alloy_code = data.alloy_code
                    this.ruleForm.data_source = data.data_source
                    this.ruleForm.sample_status = data.sample_status
                    this.ruleForm.equipment_name = data.equipment_name
                    this.ruleForm.equipment_manufacturer = data.equipment_manufacturer
                    this.ruleForm.device_model = data.device_model
                    this.ruleForm.temperature = data.temperature
                    this.ruleForm.sample_range = data.sample_range
                    this.ruleForm.sample_width = data.sample_width
                    this.ruleForm.sample_thickness = data.sample_thickness
                    this.ruleForm.open_depth = data.open_depth
                    this.ruleForm.open_shape = data.open_shape
                    this.ruleForm.fracture_toughness = data.fracture_toughness
                  })
                  .catch((error) => {
                    console.log('Error', error.message)
                  })
            }
          })
          .catch((error) => {
            console.log('Error', error.message)
            this.ruleForm.alloy_code = ''
          })
    },
    handleFinish(values) {
      this.submitting = true
      const formData = new FormData()
      formData.append('sample_name', values.sample_name)
      formData.append('alloy_code', values.alloy_code)
      formData.append('data_source', values.data_source)
      formData.append('sample_status', values.sample_status)
      formData.append('equipment_name', values.equipment_name)
      formData.append('equipment_manufacturer', values.equipment_manufacturer)
      formData.append('device_model', values.device_model)
      formData.append('temperature', values.temperature)
      formData.append('sample_range', values.sample_range)
      formData.append('sample_width', values.sample_width)
      formData.append('sample_thickness', values.sample_thickness)
      formData.append('open_depth', values.open_depth)
      formData.append('open_shape', values.open_shape)
      formData.append('fracture_toughness', values.fracture_toughness)
      if (this.url !== '') {
        this.axios
            .put(this.url, formData)
            .then(() => {
              this.submitting = false
              message.success('修改成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('修改失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      } else {
        this.axios
            .post('/property_management/fracture_property/', formData)
            .then(() => {
              this.submitting = false
              message.success('添加成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('添加失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      }
    },
  },
}
</script>
